package com.hand.cloud.b2b.taobao.impl;

import de.hybris.platform.core.model.order.OrderModel;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hand.cloud.b2b.daos.EPOrderDAO;
import com.hand.cloud.b2b.daos.OrderDAO;
import com.hand.cloud.b2b.daos.TBTradeDAO;
import com.hand.cloud.b2b.model.EPOrderModel;
import com.hand.cloud.b2b.model.TB_TradeModel;
import com.hand.cloud.b2b.taobao.DefaultProperties;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.response.TradeFullinfoGetResponse;


public class TradeCreate
{

	public static Logger LOG = Logger.getLogger(TradeCreate.class);

	@Autowired
	private TBTradeDAO tbTradeDAO;

	@Autowired
	private EPOrderDAO epOrderDAO;

	@Autowired
	private OrderDAO orderDAO;

	TmcClient client;

	Queue<Trade> orderQueue = new ConcurrentLinkedQueue<Trade>();

	Object queueLock = new Object();

	boolean running = false;

	int orderHandleNum = 1;

	ExecutorService orderHandleService;

	public void execute()
	{

		System.out.println("***********linjinxiao1*******************");
		running = true;

		orderHandleService = Executors.newFixedThreadPool(orderHandleNum);
		for (int i = 0; i < orderHandleNum; i++)
		{
			final OrderHandle orderHandle = new OrderHandle();
			orderHandleService.execute(orderHandle);
		}

		//		final String appKey = "1021820838";
		//		final String appSecret = "sandbox2a3b4dbc7f7139ac4d7304bdf";
		//		final String sessionKey = "6100b061ebcb221e644762f1c1f7f418ca601a94c65ce373638380614";
		//		final String serverUrl = "http://gw.api.tbsandbox.com/router/rest";


		client = new TmcClient("ws://mc.api.tbsandbox.com/", DefaultProperties.appKey, DefaultProperties.appSecret, "default");

		final TaobaoClient tbClient = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);

		client.setMessageHandler(new MessageHandler()
		{
			public void onMessage(final Message message, final MessageStatus status)
			{
				try
				{
					System.out.println("receive a order message!");
					final String jsonMessage = message.getContent();
					//					final JSONObject jsonObject = new JSONObject(jsonMessage);
					//					long tid = jsonObject.getLong("tid");


					final long tid = 192390290386705L;
					System.out.println("tid：" + tid);
					System.out.println("jsonMessage：" + jsonMessage);
					// 默认不抛出异常则认为消息处理成功

					createOrderDetails(tbClient, tid);
				}
				catch (final Exception e)
				{
					e.printStackTrace();
					status.fail();// 消息处理失败回滚，服务端需要重发
				}
			}
		});
		try
		{
			client.connect();

			// 正式环境可以直接注释
			//			final long min10 = 1000 * 30;
			//			Thread.sleep(min10);
		}
		catch (final Exception e)
		{
			e.printStackTrace();
		}
	}

	public void shutdown()
	{
		System.out.println("*****TradeCreate shutdown*********");
		running = false;

		if (client != null)
		{
			client.close();
		}
		//需要考虑还有订单没处理完的情况。
		if (orderHandleService != null)
		{
			orderHandleService.shutdownNow();
		}
	}

	private void createOrderDetails(final TaobaoClient client, final long tid)
	{

		LOG.info("--------DefaultTradeCreationService---createOrderDetails-------------");

		final TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
		req.setFields("seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		req.setTid(tid);

		try
		{
			final String sessionKey = DefaultProperties.sessionKey;
			final TradeFullinfoGetResponse response = client.execute(req, sessionKey);

			System.out.println("getTrade:" + response.getBody());

			final Trade trade = response.getTrade();

			orderQueue.add(trade);

			synchronized (queueLock)
			{
				queueLock.notifyAll();
			}

			//			// 打印信息
			//			printTrade(trade);
			//			// 创建订单
			//			createOrderByTrade(trade);
		}
		catch (final ApiException e)
		{
			e.printStackTrace();
		}
	}



	private void createOrderByTrade(final Trade trade)
	{

		//		Registry.activateMasterTenant();

		// trade测试数据
		//		final Trade trade1 = initTrade();
		// 创建tbOrder
		final TB_TradeModel tbTrade = this.tbTradeDAO.createTBTrade(trade);
		System.out.println("tbTradePK:" + tbTrade.getPk());

		final EPOrderModel epOrder = this.epOrderDAO.createEpOrder(tbTrade);
		System.out.println("epOrderPK:" + epOrder.getPk());

		final OrderModel orderModel = this.orderDAO.createOrder(epOrder);
		System.out.println("orderPK:" + orderModel.getPk());
		System.out.println("orderCode:" + orderModel.getCode());
	}

	private void printTrade(final Trade trade)
	{
		System.out.println("trade.getBuyerAlipayNo(): " + trade.getBuyerAlipayNo());
		System.out.println("trade.getDiscountFee(): " + trade.getDiscountFee());
		System.out.println("trade.getHasPostFee(): " + trade.getHasPostFee());
		System.out.println("trade.getInvoiceName(): " + trade.getInvoiceName());
		System.out.println("trade.getInvoiceType(): " + trade.getInvoiceType());
		System.out.println("trade.getPayment(): " + trade.getPayment());
		System.out.println("trade.getPointFee(): " + trade.getPointFee());
		System.out.println("trade.getPostFee(): " + trade.getPostFee());
		System.out.println("trade.getSellerCodFee(): " + trade.getSellerCodFee());
		System.out.println("trade.getSnapshotUrl(): " + trade.getSnapshotUrl());
		System.out.println("trade.getStatus(): " + trade.getStatus());
		System.out.println("trade.getTotalFee(): " + trade.getTotalFee());
		System.out.println("trade.getType(): " + trade.getType());

		for (final Order order : trade.getOrders())
		{
			System.out.println("order.getOuterIid():" + order.getOuterIid());
		}
	}

	public Trade initTrade()
	{
		final Trade trade = new Trade();
		final Order order = new Order();
		final List<Order> orders = new ArrayList<Order>();

		trade.setBuyerAlipayNo("tbtest1063");
		final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		final ParsePosition pos = new ParsePosition(0);
		final Date date = formatter.parse("2000-01-01 00:00:00", pos);
		trade.setCreated(date);
		trade.setDiscountFee("200.07");
		trade.setHasPostFee(true);
		trade.setInvoiceName("淘宝");
		trade.setInvoiceType("水果");
		trade.setPayment("200");
		trade.setPointFee((long) 0);
		trade.setPostFee("15");
		trade.setSellerCodFee("12.07");
		trade.setSnapshotUrl("T1mURbXopZXXXe3rL");
		trade.setStatus("TRADE_NO_CREATE_PAY");
		trade.setTotalFee("290");
		trade.setType("fixed");

		trade.setReceiverAddress("Pudong");
		trade.setReceiverCity("SH");
		trade.setReceiverDistrict("Pudong");
		trade.setReceiverMobile("111111111");
		trade.setReceiverName("Cynthia");
		trade.setReceiverPhone("12300000");
		trade.setReceiverState("SH");
		trade.setReceiverZip("210210");

		order.setNum((long) 30);
		order.setPrice("200");
		order.setTotalFee("6000");
		order.setItemMealName("M8原装电池");
		orders.add(order);
		trade.setOrders(orders);
		return trade;
	}

	class OrderHandle implements Runnable
	{

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			while (running)
			{
				final Trade trade = orderQueue.poll();
				if (trade == null)
				{
					synchronized (queueLock)
					{
						try
						{
							queueLock.wait();
						}
						catch (final InterruptedException e)
						{
							e.printStackTrace();
						}
					}
				}
				else
				{
					try
					{
						// 打印信息
						printTrade(trade);
						// 创建订单
						createOrderByTrade(trade);
					}
					catch (final Throwable e)
					{
						System.out.println("***** catch error...");
						e.printStackTrace();
					}
				}
			}

		}

	}





	public static void main(final String[] args)
	{
		final TradeCreate tc = new TradeCreate();
		tc.execute();

	}
}
